<template>
  <div class="index_container">
    <div class="staff_title">仓库管理</div>
    <div class="staff_top">
      <div></div>
      <div>
        <el-button @click="addStaff" class="staff_btn">添加商品</el-button>
      </div>
    </div>
    <div>
      <myTabel
          stripe
          v-if="showMyTable"
          :columnData="columnData"
          :data="tableData"
      >
        <el-table-column label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.image" width="100px" height="auto" alt=""/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="190px">
          <template slot-scope="scope">
            <el-button type="text" @click="editWareHouse(scope.row)">
              修改
            </el-button
            >
            <el-button type="text el-button--del" @click="del(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </myTabel>
      <el-dialog :visible="isVisible" :title="title" width="660px"
                 @close="cancal"
      >
        <div class="dialog_content">
          <el-form
              :inline="true"
              label-position="right"
              :model="addWareHouseForm"
              label-width="80px"
          >
            <el-form-item label="名称" prop="name">
              <el-input v-model="addWareHouseForm.name"></el-input>
            </el-form-item>
            <el-form-item label="款号" prop="styleNumber">
              <el-input v-model="addWareHouseForm.styleNumber"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="image">
              <el-upload
                  class="avatar-uploader"
                  :action="uploadApi"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
              >
                <!-- :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload" -->
                <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancal">取 消</el-button>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
        </span>
      </el-dialog>

      <!--      库存模态框-->
      <el-dialog :visible.sync="showStock" :title="title" width="80vw"
                 @close="cancal"
      >
        <div style="display: flex">
          <div style="flex: 5">
            <el-input type="textarea" v-model="textPrice" @input="change"></el-input>
            <el-button type="primary" @click="readBoardPrice(true)">覆盖黏贴</el-button>
            <el-button type="primary" @click="readBoardPrice(false)">拼接黏贴</el-button>
            <el-button type="primary" @click="priceAnalysis">价格解析</el-button>

            <el-table :data="tablePriceDetails">
              <el-table-column label="部位" width="80">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.position"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="工序">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.process"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="价格" width="80">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>

              <el-table-column
                  label="删除">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="handleDeletePrice(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>


            </el-table>


          </div>
          <div  style="flex: 1"></div>
          <div  style="flex: 5">
            <el-input type="textarea" v-model="text" @input="change"></el-input>
            <el-button type="primary" @click="readBoard(true)">覆盖黏贴</el-button>
            <el-button type="primary" @click="readBoard(false)">拼接黏贴</el-button>
            <el-button type="primary" @click="updateDetails">确 定</el-button>

            <el-table :data="tableDataDetails" style="width: 100%">
              <el-table-column label="部位" prop="position" width="80">
              </el-table-column>
              <el-table-column label="扎号" prop="batch_number" width="80">
              </el-table-column>
              <el-table-column label="尺码" prop="size" width="80">
              </el-table-column>
              <el-table-column label="件数" prop="quantity" width="80">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantity" style="width: 80px"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="wage" width="80">
              </el-table-column>
              <el-table-column label="颜色" prop="color" width="80">
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.is_over == 1" type="success" @click="handleEditStatus(scope.row)">已登记</el-tag>
                  <el-tag v-else type="warning" @click="handleEditStatus(scope.row)">待登记</el-tag>
                </template>
              </el-table-column>
              <el-table-column width="50px"
                  label="删除">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import {
  getLibrary,
  addLibrary,
  deleteLibrary,
} from "@/request/api/warehouseManagementApi/warehouseManagementApi";
import myTabel from "@/components/myTable/index.vue";

export default {
  components: {myTabel},
  computed: {
    uploadApi() {
      return window.location.origin + "/admin/api/uploadFile";
    },
  },
  data() {
    return {
      tablePriceDetails: [],
      textPrice: "",
      text: "",
      product_id: "",
      tableData: [],
      tableDataDetails: [],
      showStock: false,
      isVisible: false,
      showMyTable: true,
      staffForm: {
        username: "",
      },
      imageUrl: "",
      addWareHouseForm: {
        name: "",
        styleNumber: "",
        image: "",
      },
      columnData: [
        {
          prop: "product_name",
          label: "产品名称",
          "min-width": "120",
        },
        {
          prop: "style_number",
          label: "款号",
          "min-width": "120",
        },
        {
          prop: "count",
          label: "库存",
          "min-width": "80",
        },
        {
          prop: "count",
          label: "操作库存",
          "min-width": "80",
          render: (h, row) => {
            return h("el-button", {
              props: {
                type: "text",
                size: "small"
              },
              on: {
                click: () => {
                  this.product_id = row.id;
                  console.log("查看按钮被点击了，当前行数据为：", row);
                  // 这里可以编写打开弹窗等操作的逻辑
                  this.showStock = true;
                  this.$axios.get("/auth/getLibraryDetails", {params: {id: row.id}}).then((res) => {
                    console.log(res, 'res')
                    if (res.data.code === 200) {
                      this.tableDataDetails = res.data.data.data
                      this.tablePriceDetails = res.data.data.dataPrice
                    }
                  });


                }
              }
            }, "查看");
          }
        }
      ],
      title: "",
    };
  },
  created() {
    this.getLibraryList();
  },

  methods: {
    priceAnalysis() {
      this.tableDataDetails.forEach((item, index) => {

        let data = this.tablePriceDetails.find(item2 => item2.position === item.position)
        if (data) {
          item.wage = data.price
        }
      })
    },
    handleDeletePrice(index, row) {
      this.tablePriceDetails.splice(index, 1)
    },

    readBoardPrice(isCover = false) {
      let rows = this.textPrice.split('\n')

      console.log(rows)
      rows = rows.filter(item => item !== '')

      rows = rows.map(item => item.split('\t'))
      const data = []

      rows.forEach((item, index) => {
        let obj = {}
        obj.position = item[0]
        obj.process = item[1]
        console.log(item)
        obj.price = item[item.length-1]
        data.push(obj)
      })
      if (isCover) {
        this.tablePriceDetails = data
      } else {
        this.tablePriceDetails = this.tablePriceDetails.concat(data)
      }



      console.log(this.tablePriceDetails)
    },







    updateDetails() {
      this.$axios.post("/auth/addInventory", {
        data: JSON.stringify(this.tableDataDetails),
        dataPrice: JSON.stringify(this.tablePriceDetails),
        id: this.product_id
      }).then((res) => {
        console.log(res, 'res')
        if (res.data.code === 200) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.showStock = false;
          this.getLibraryList();
        }
      });
    },

    //修改登记状态
    handleEditStatus(row) {
      row.is_over = row.is_over === 1 ? 0 : 1;
    },


    handleDelete(index, row) {
      this.tableDataDetails.splice(index, 1)
    },
    change(value) {
      //读取粘贴板内容
      console.log(value)
      // this.readBoard(true, value)
    },


    readBoard(isCover = false,text2) {
      // let rows2 = text2.split('\n')
      //
      // console.log(rows2)
      // console.log('readBoard', navigator.clipboard)
      // let clipboard = navigator.clipboard || {
      //   writeText: (text) => {
      //     let copyInput = document.createElement('input');
      //     copyInput.value = text;
      //     document.body.appendChild(copyInput);
      //     copyInput.select();
      //     document.execCommand('copy');
      //     document.body.removeChild(copyInput);
      //   },
      //   readText: () => {
      //     let copyInput = document.createElement('input');
      //     document.body.appendChild(copyInput);
      //     copyInput.select();
      //     document.execCommand('paste');
      //     let text = copyInput.value;
      //     document.body.removeChild(copyInput);
      //     return Promise.resolve(text);
      //   }
      // }
      let text = this.text
      // if (clipboard) {
      //    text = (await clipboard.readText()).toString();
      //   console.log(text.toString())
      //   // this.$message.success('复制成功');
      // }
      if (isCover) {
        this.tableDataDetails = []
      }
      // console.log(text)

      let rows = text.split('\n')

      console.log(rows)
      rows = rows.filter(item => item !== '')

      rows = rows.map(item => item.split('\t'))

      rows.forEach((item, index) => {
        let obj = {}
        obj.position = item[0]
        obj.batch_number = item[1]
        obj.size = item[2]
        obj.quantity = item[3]
        obj.wage = item[4]
        obj.color = item[5] || '/'
        obj.is_over = item[6] || 0

        this.tableDataDetails.push(obj)
      })
      console.log(this.tableDataDetails)
      // if (navigator.clipboard) {
      //   navigator.clipboard.readText().then(text => {
      //     console.log(text.toString())
      //     // console.log(isCover)
      //     if (isCover) {
      //       this.tableDataDetails = []
      //     }
      //     // console.log(text)
      //
      //     let rows = text.split('\r\n')
      //     // console.log(rows)
      //     rows = rows.filter(item => item !== '')
      //
      //     rows = rows.map(item => item.split('\t'))
      //
      //     rows.forEach((item, index) => {
      //       let obj = {}
      //       obj.position = item[0]
      //       obj.batch_number = item[1]
      //       obj.size = item[2]
      //       obj.quantity = item[3]
      //       obj.wage = item[4]
      //       obj.color = item[5] || '/'
      //       obj.is_over = item[6] || 0
      //
      //       this.tableDataDetails.push(obj)
      //     })
      //     console.log(this.tableDataDetails)
      //   }).catch(err => {
      //     console.error('Failed to read clipboard contents: ', err);
      //   });
      // } else {
      //   // console.log('不支持')
      // }


    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.addWareHouseForm.image = res.data.url;
    },
    handleSearch() {
      if (this.staffForm.username) {
        this.tableData = this.tableData.filter((item) => {
          return item.username.includes(this.staffForm.username);
        });
      } else {
        this.getUserList();
      }
    },

    // 获取用户列表
    getLibraryList() {
      getLibrary().then((res) => {
        this.tableData = res.data;
      });
    },
    // 打开弹框
    addStaff() {
      this.title = "添加商品";
      this.isVisible = true;
    },
    // 添加用户
    submitAdd() {
      const data = {
        ...this.addWareHouseForm,
      };
      if (data.id) {
        this.$axios.post("/auth/updateLibrary", data).then((res) => {
          console.log(res, 'res')
          if (res.data.code === 200) {
            this.$message({
              type: "success",
              message: "修改成功",
            });
            this.cancal();
            this.getLibraryList();
          }
        });


      } else {
        addLibrary(data).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.cancal();
            this.getLibraryList();
          }
        });
      }
      console.log(this.addWareHouseForm);
    },
    // 删除用户
    del(val) {
      const data = {
        id: val.id,
      };
      deleteLibrary(data).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.getLibraryList();
        }
      });
    },
    // 修改用户
    editWareHouse(val) {
      this.addWareHouseForm = {
        name: val.product_name,
        styleNumber: val.style_number,
        image: val.image,
        id: val.id,
      };
      this.imageUrl = window.location.origin + val.image;
      this.title = "编辑商品";
      this.isVisible = true;
    },
    // 关闭弹框
    cancal() {
      this.isVisible = false;
      this.addWareHouseForm = {
        name: "",
        styleNumber: "",
        image: "",
      };
    },
  },
  mounted() {
  },
};
</script>

<style lang="scss">
.staff_title {
  font-size: 24px;
  font-weight: 500;
}

.staff_top {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;

  .staff_btn {
    height: 32px;
    line-height: 10px;
  }
}

.dialog_content {
  width: 400px;
  margin: 0 auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
